package com.peng._05mvcboot02.controller;

import com.peng._05mvcboot02.common.response.JsonResult;
import com.peng._05mvcboot02.mapper.UserMapper;
import com.peng._05mvcboot02.pojo.dto.AddUserDTO;
import com.peng._05mvcboot02.pojo.entity.User;
import com.peng._05mvcboot02.pojo.vo.UserListVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @Author peng
 * @Date 2024-04-22 11:14
 */
@Slf4j
@RestController
@RequestMapping("/v1/user")
@Api(tags = "用户管理")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/insert")
    @ApiOperation("添加用户")
    public JsonResult insertUser(AddUserDTO addUserDTO) {
        log.debug("addUserDTO:{}", addUserDTO);
        //校验username是否重复
        List<User> user1 = userMapper.selectUserByUsername(addUserDTO.getUsername());
        if (!user1.isEmpty()) {
            return JsonResult.success("用户名已存在");
        }
        User user = new User();
        BeanUtils.copyProperties(addUserDTO, user);
        user.setCreated(new Date());
        int i = userMapper.insertUser(user);
        if (i > 0) {
            System.out.println("插入" + i + "条数据成功");
            return JsonResult.success("插入" + i + "条数据成功");
        }
        return JsonResult.error();
    }

    @GetMapping("/userList")
    @ApiOperation("查询所有用户")
    public JsonResult selectAllUser() {
        List<UserListVO> userList = userMapper.selectAllUser();
        return JsonResult.success(userList);
    }

    @GetMapping("/delete/{id}")
    @ApiOperation("删除用户")
    @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Integer")
    public JsonResult deleteUser(@PathVariable Integer id) {
        log.debug("userid:{}", id);
        int i = userMapper.deleteUserById(id);
        if (i > 0) {
            return JsonResult.success("删除用户成功");
        }
        return JsonResult.error();
    }

    @PostMapping("/update")
    @ApiOperation("更新用户信息")
    public JsonResult updateUser(User user) {
        log.debug("user:{}", user);
        int i = userMapper.updateUser(user);
        if (i > 0) {
            return JsonResult.success("更新用户成功");
        }
        return JsonResult.error();
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id查询用户")
    public JsonResult getUserById(@PathVariable Integer id) {
        log.debug("userid:{} &&&&&***", id);
        return JsonResult.success(userMapper.selectUserById(id));
    }
}
